package org.ztr.yanai.blog.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/11/22 14:30
 * @Description: 缓存配置类，配置Spring Cache使用Redis
 * @Version: 1.0
 */
@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * 默认缓存过期时间（小时）
     */
    private static final long DEFAULT_EXPIRE_HOURS = 24;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 默认缓存配置
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(DEFAULT_EXPIRE_HOURS))
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .disableCachingNullValues();

        // 针对不同缓存的个性化配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();

        // 用户信息缓存：1小时
        configMap.put("user", defaultConfig.entryTtl(Duration.ofHours(1)));

        // 文章列表缓存：30分钟
        configMap.put("post", defaultConfig.entryTtl(Duration.ofMinutes(30)));

        // 分类标签缓存：2小时
        configMap.put("category", defaultConfig.entryTtl(Duration.ofHours(2)));
        configMap.put("tag", defaultConfig.entryTtl(Duration.ofHours(2)));

        // 热门文章缓存：10分钟
        configMap.put("hot", defaultConfig.entryTtl(Duration.ofMinutes(10)));

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(configMap)
                .transactionAware()
                .build();
    }
}
